//
// Created by LvenLiu on 2022/3/25.
//

#include "JNICallback.h"

JNICallback::JNICallback(JavaVM *vm, JNIEnv *env, jobject obj) {
    this->vm = vm; // 无限制
    this->env = env; // 可以跨函数，不可以跨线程
    // jobject不能跨越线程，不能跨越函数，必须全局引用
    this->obj = env->NewGlobalRef(obj);
    // Java层 FFPlayer.java
    jclass video_player_cls = env->GetObjectClass(obj);
    this->jmd_prepared = env->GetMethodID(video_player_cls, "onPrepared", "()V");
    this->jmd_error = env->GetMethodID(video_player_cls, "onError", "(ILjava/lang/String;)V");
}

JNICallback::~JNICallback() {
    vm = 0;
    if (env && obj) {
        env->DeleteGlobalRef(obj);
    }
    obj = 0;
    env = 0;
    jmd_prepared = 0;
    jmd_error = 0;
}

void JNICallback::onPrepared(int thread_mode) {
    if (thread_mode == THREAD_MAIN) {
        env->CallVoidMethod(obj, jmd_prepared);
    } else if (thread_mode == THREAD_CHILD) {
        JNIEnv *env_child;
        vm->AttachCurrentThread(&env_child, 0);
        env_child->CallVoidMethod(obj, jmd_prepared);
        vm->DetachCurrentThread();
    }
}


void JNICallback::onError(int thread_mode, int error_code, char *msg) {
    if (thread_mode == THREAD_MAIN) {
        env->CallVoidMethod(obj, jmd_error, error_code, env->NewStringUTF(msg));
    } else if (thread_mode == THREAD_CHILD) {
        JNIEnv *env_child;
        vm->AttachCurrentThread(&env_child, 0);
        env_child->CallVoidMethod(obj, jmd_error, error_code, env_child->NewStringUTF(msg));
        vm->DetachCurrentThread();
    }
}
